//
//  AppDelegate.m
//  HondaPro_2
//
//  Created by Eric on 13-5-29.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "AppDelegate.h"
#import <Bugly/Bugly.h>
#import "MainViewController.h"
#import "HelpClass.h"
#import "CarCalendarQueryViewController.h"
#import <AdSupport/AdSupport.h>
#import "NSData+Encryption.h"
#import "MyAFNetWorkManager.h"
#import "NetworkManager.h"
#import "SettingViewController.h"
#import "DealerModle.h"
#import "YYAvoidCrash.h"

#define GET_SHOU_HOU_VERSION_TASK_STATUS_   10000


@implementation AppDelegate

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 当真机连接Mac调试的时候把这些注释掉，否则log只会输入到文件中，而不能从xcode的监视器中看到。
    // 如果是真机就保存到Document目录下的drm.log文件中
    /**
     UIDevice *device = [UIDevice currentDevice];
     
     if (![[device model] isEqualToString:@"iPad Simulator"]) {
     // 开始保存日志文件
     [self redirectNSlogToDocumentFolder];
     }
     **/
    
    /*
     //通用代码表使用方法
    NSDictionary *dicTmp = [HelpClass returnTheDataByJsonFileAndJustForTestWithFileName:@"codeA" andType:@"json"];
    NSLog(@"%@",dicTmp);
     */
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.viewController = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
    self.naVC = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = self.naVC;

    self.logState = NO;
    [Bugly startWithAppId:@"acd4b299a9"];
    [YYAvoidCrash becomeEffective];

    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *realPath = [documentPath stringByAppendingPathComponent:@"Config.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:realPath]) {
        
        NSMutableDictionary *dictplist = [[NSMutableDictionary alloc ] init];
        //设置属性值
        [dictplist setObject:@"" forKey:@"ip"];
        NSString*adId =[[[ASIdentifierManager sharedManager] advertisingIdentifier]UUIDString];
        
        [dictplist setObject:adId forKey:@"mid"];
        
        //将当前程序的 version 写入属性列表
        [dictplist setObject:APP_VERSION_ forKey:@"GHAC_AppVersion"];
        
        //写入文件
        [dictplist writeToFile:realPath atomically:YES];
        self.currentIp =@"";
        
        
    } else {
        
        NSString *ipStr = [[NSDictionary dictionaryWithContentsOfFile:realPath] objectForKey:@"ip"];
        self.currentIp =ipStr;
    }
   NSString *ipStr2 = [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"];
    if (![ipStr2 isKindOfClass:[NSString class]] || 0 == ipStr2.length) {
        //弹出ip设置
        UIAlertView* setIPAlertView = [[UIAlertView alloc] initWithTitle:@"设置IP" message:nil delegate:self cancelButtonTitle:@"完成" otherButtonTitles:nil, nil];
        setIPAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
        
        UITextField* textField = [setIPAlertView textFieldAtIndex:0];
        textField.delegate = self;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        [setIPAlertView show];
    }
    else {
        [[MainViewController sharedViewController] systemLogin];
        [SettingViewController shareInstance];//设置界面中创建需要更新车辆的消息相应事件
        [ConfigCodeHelper shareInstance];//初始化缓存中的数据，以及发送需要更新的车辆消息
    }

    
    [self.window makeKeyAndVisible];
    
//    //检查更新
//    NSString* url = [NSString stringWithFormat:@"http://%@/paddata/source.txt", self.currentIp];
//    NetworkTask * task = [[NetworkTask alloc] initWithGetUrl:url getArgs:nil];
//    NSLog(@"%@",task.resultDict);
    
    //更新前的版本号为最新版本号
    [HelpClass saveVersion:APP_VERSION_];

    return YES;
}
//- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
//    if (self.bAlbumListViewStatus)
//        //全局变量，定义是否打开相册
//        return UIInterfaceOrientationMaskAll;
//    else
//        return UIInterfaceOrientationLandscapeLeft|UIInterfaceOrientationLandscapeRight;
//}



-(void)redirectNSlogToDocumentFolder{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirctor = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"dr.log"];
    NSString *logFilePath=[documentDirctor stringByAppendingPathComponent:fileName];
    //先删除除已存在的文件
    NSFileManager *defaulManager = [NSFileManager defaultManager];
    [defaulManager removeItemAtPath:logFilePath error:nil];
    //将log输入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
    
    //最后配置共享文件夹：在应用程序的Info.plist文件中添加UIFileSharingEnabled键，并将键值设置为YES
}



#pragma mark - UITextFieldDelegate   设置键盘0~9
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return ([string isEqualToString:[string stringByReplacingOccurrencesOfString:@"[^0-9.:]*" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)]]
            ? YES
            : NO);
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    UITextField* textField = [alertView textFieldAtIndex:0];
    self.currentIp = [textField.text copy];

    
    if(textField.text.length>0)
    {
        [SVProgressHUD showWithStatus:@"加载中..."];
        [MyAFNetWorkManager getWithAction:@"QUERY_ALL_ASC_INFO" andipstr:textField.text finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            [SVProgressHUD dismiss];
            NSLog(@"设置IP：%@",obj);
            if (error == nil)
            {
                if([[obj valueForKey:@"SUCCESS"]intValue]==1)
                {
                    NSMutableArray *dealerArr=[NSMutableArray array];
                    
                    NSMutableArray *Lname = [[NSMutableArray alloc]init];
                    
                    NSMutableArray *Lcode = [[NSMutableArray alloc]init];
                    
                    id dataArr=[obj objectForKey:@"TM_ASC_BASICINFO"];
                    if([dataArr isKindOfClass:[NSArray class]])
                    {
                        for (NSDictionary *dic in dataArr) {
                            DealerModle *dealer=[[DealerModle alloc]init];
                            dealer.DealerCode=[dic objectForKey:@"DealerCode"];
                            dealer.AscName=[dic objectForKey:@"AscName"];
                            dealer.AscShortname=[dic objectForKey:@"AscShortname"];
                            dealer.EntityCode=[dic objectForKey:@"EntityCode"];
                            
                            [dealerArr addObject:dealer];
                            
                            [Lname addObject:[dic objectForKey:@"DealerCode"]];
                            [Lcode addObject:[dic objectForKey:@"EntityCode"]];
                        }
                        
                        if([dealerArr count]>0)
                        {
                            //DealerModle *dealer=[dealerArr objectAtIndex:0];
                            //                                    [_login.siteBtn setTitle:dealer.AscName forState:UIControlStateNormal];
                            //                                    _login.ENTITY_CODE=dealer.EntityCode;
                            
                        }
                        
                        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
                        NSData *dealerdata = [NSKeyedArchiver archivedDataWithRootObject:dealerArr];
                        [user setObject:dealerdata forKey:@"dealerdata"];
                        
                        [user setObject:Lname forKey:@"name"];
                        [user setObject:Lcode forKey:@"code"];
                        
                        [user setObject:textField.text forKey:@"ip"];
                        [user synchronize];
                    }
                }
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }
        }];
    }
    else{
        [SVProgressHUD showErrorWithStatus:@"IP不能为空"];
    }
}

#pragma mark -
- (void)onTaskSuccessForSettingVersion:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    
    NSLog(@"%@",task.resultDict);
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    [HelpClass saveVersion:[task.resultDict objectForKey:@"GHAC_AppVersion"]];
    [[NetworkingViewController sharedController] dismissNetworking];
}

- (void)onTaskFailForSettingVersion:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    [[NetworkingViewController sharedController] dismissNetworking];
}

#pragma mark -
- (void)onTaskSuccessabcs:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    
    NSLog(@"%@",task.resultDict);
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
//    if (![_strFlagForSettingVersion isEqualToString:@"versionHasSetted"])
//    {
//        NSString *url = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=http://%@/PadData/%@/GHAC_AppVersion.txt",self.currentIp,APP_AND_SETUP_FILE_FOLDER_NAME_];
//        NetworkTask * task = [[NetworkTask alloc] initWithGetUrl:url getArgs:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskSuccess:) name:NetworkTask_NotificationName_OnSuccess object:task];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskFail:) name:NetworkTask_NotificationName_OnFail object:task];
//        [[NetworkManager getInstance] startTaskAsync:task];
//
//        //设置成
//        _strFlagForSettingVersion = @"versionHasSetted";
//        _strFlagForSettingVersionFinished = @"versionHasSetted";
//        
//        return;
//    }
//    else if ([_strFlagForSettingVersionFinished isEqualToString:@"versionHasSetted"])
//    {
//        [HelpClass saveVersion:[task.resultDict objectForKey:@"GHAC_AppVersion"]];
//        _strFlagForSettingVersionFinished = @"";
//        [[NetworkingViewController sharedController] dismissNetworking];
//        
//        return;
//    }
    
   if (200 == task.statusCode) {//成功设置IP
       
                 [[NetworkingViewController sharedController] showNetworkingWithTitle:@"设置成功!" content:nil activiting:NO enableDismiss:YES];
        

        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *realPath = [documentPath stringByAppendingPathComponent:@"Config.plist"];
        
        NSMutableDictionary *dictplist = [NSDictionary dictionaryWithContentsOfFile:realPath];
        
        //设置属性值
        [dictplist setObject:self.currentIp forKey:@"ip"];
        
        //写入文件
        [dictplist writeToFile:realPath atomically:YES];
        
        [[NSUserDefaults standardUserDefaults] setObject:self.currentIp forKey:@"ip"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [NetworkManager getInstance].host = self.currentIp;
        
        [SettingViewController shareInstance];//设置界面中创建需要更新车辆的消息相应事件
        [ConfigCodeHelper shareInstance];//初始化缓存中的数据，以及发送需要更新的车辆消息
        
      
        [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:1.5];
        
    } else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP" message:@"设置失败，请重新设置!" delegate:self cancelButtonTitle:@"完成" otherButtonTitles:nil, nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField* textField = [alert textFieldAtIndex:0];
        textField.delegate = self;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        [alert show];
        //        SafeRelease(alert);
        [[NetworkingViewController sharedController] dismissNetworking];
    }
    //    SafeRelease(_ipConfig);
    
    //获取最新版本并更新本地版本信息
//    NSString* urlForSettingVersion = [NSString stringWithFormat:@"http://%@/PadData/%@/GHAC_AppVersion.txt", self.currentIp,APP_AND_SETUP_FILE_FOLDER_NAME_];
//    NetworkTask * taskForSettingVersion = [[NetworkTask alloc] initWithGetUrl:urlForSettingVersion getArgs:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskSuccessForSettingVersion:) name:NetworkTask_NotificationName_OnSuccess object:taskForSettingVersion];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskFailForSettingVersion:) name:NetworkTask_NotificationName_OnFail object:taskForSettingVersion];
//    [[NetworkManager getInstance] startTaskAsync:taskForSettingVersion];
}

- (void)onTaskFailabcs:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
//    if ([_strFlagForSettingVersion isEqualToString:@"versionHasSetted"])
//    {
//        [[NetworkingViewController sharedController] dismissNetworking];
//        return;
//    }
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP" message:@"设置失败，请检查网络!" delegate:self cancelButtonTitle:@"完成" otherButtonTitles:nil, nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField* textField = [alert textFieldAtIndex:0];
    textField.delegate = self;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [alert show];
    //    SafeRelease(alert);
    [[NetworkingViewController sharedController] dismissNetworking];
    //    SafeRelease(_ipConfig);
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//检查更新并更新,(主要检查主界面最右边的四个模块的资源是否有更新)
-(void)updateServerDataSourceForTrunk
{
    NSString* url = [NSString stringWithFormat:@"http://%@/paddata/source.txt", self.currentIp];
    NetworkTask * task = [[NetworkTask alloc] initWithGetUrl:url getArgs:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskSuccess:) name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTaskFail:) name:NetworkTask_NotificationName_OnFail object:task];
    [[NetworkManager getInstance] startTaskAsync:task];
}

@end
